#include "UdpServer.hpp"
#include "Log.hpp"
#include "Thread.hpp"

using namespace ThreadModule;

int sockfd = 0;
std::string server_ip;
uint16_t server_port = 0;
pthread_t id;

void Receive()
{
    while(true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t s = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)&peer,&len);//本地客户端 接收 远端服务器发送的消息，远端的数据 ip 端口 分别保存到buffer peer中
        std::cout << "zhi xing last" << std::endl;
        
        if(s>0)
        {
            buffer[s] = 0;
            std::cerr << buffer << std::endl;
        }
    }
}

void Send()
{
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);//将系统默认字节序转为网络字节序
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());//将c风格的点分十进制ip 转为 四字节风格的ip
    
    while(true)
    {
        std::string input;
        std::cout << "请输入：" << std::endl;
        std::getline(std::cin,input);
        int n = sendto(sockfd,input.c_str(),input.size(),0,(sockaddr*)&server,sizeof(server));//本地客户端的数据 发送到目标IP和端口号中
        if(n < 0)
        {
            LOG(LogLevel::DEBUG) << "sendto error  " ;
            exit(1);
        }
        if(input == "QUIT")
        {
            pthread_cancel(id);
            break;
        }
    }
}

int main(int args, char* argv[])
{
    if(args != 3)
    {
        std::cout << "you should enter : target ip and target port" << std::endl;
        exit(2);
    }
    server_ip = argv[1];
    server_port = std::stoi(argv[2]);//将字符串转为整型

    //1.创建socket
    sockfd = socket(AF_INET,SOCK_DGRAM,0);
    
    Thread recev(Receive);
    Thread send(Send);

    recev.Start();
    send.Start();

    id = recev.Id();

    recev.Join();
    send.Join();

    return 0;
}
